package tgc.edu.zz.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import tgc.edu.zz.dao.BlogImageDAO;
import tgc.edu.zz.utils.CommonService;
import tgc.edu.zz.vo.BlogImageVo;

@Service
public class BlogImagService  extends CommonService<BlogImageVo, Integer>{

	@Autowired
	private BlogImageDAO dao;
	private String path="c:/files/google";
	
	@Transactional
	public void saveImage(MultipartFile file, String uuid) {
		BlogImageVo img = new BlogImageVo();
		String filename = file.getOriginalFilename();//获取文件的名字
		img.setFilesname(filename);
		img.setUuid(uuid); 
		dao.save(img); //保存到数据库
		File path = new File(this.path);
		if(!path.isDirectory()) {
			path.mkdir();
		}
		File saveFile = new File(path, uuid);
		try {
			file.transferTo(saveFile);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
	}
	@Transactional
	public void download(String uuid2, HttpServletRequest request, HttpServletResponse response) {
		BlogImageVo files = findByUuid(uuid2);
		String filename = files.getFilesname();
		filename=getStr(request,filename);
		String uuid = files.getUuid();
		File file = new File(path, uuid);
		if(file.exists()) {
			FileInputStream fis;
			try {
				fis = new FileInputStream(file);
				response.setContentType("application/x-msdownload");
				response.addHeader("Content-Disposition", "attachment; filename=" + filename);
				ServletOutputStream out = response.getOutputStream();
				byte[] buf=new byte[2048];
				int n=0;
				while((n=fis.read(buf))!=-1){
					out.write(buf, 0, n);
				}
				fis.close();
				out.flush();
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}catch (IOException e) {
				e.printStackTrace();
			}
		
		}
	}
	
	private BlogImageVo findByUuid(String uuid2) {
		return dao.findByUuid(uuid2);
	}
	
	
	private String getStr(HttpServletRequest request, String filename) {
		String downloadFileName = null;
		String agent = request.getHeader("USER-AGENT");
			 try {
				 if(agent != null && agent.toLowerCase().indexOf("firefox")>0) {
				downloadFileName = "=?UTF-8?B?" + Base64Utils.encodeToString(filename.getBytes("UTF-8")) + "?=";
				 }else {
					 downloadFileName =  java.net.URLEncoder.encode(filename, "UTF-8");
				 }
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		return downloadFileName;
	}

	
}
